package com.ys.service.business.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ys.dto.AddDto;
import com.ys.entity.business.ThrCanvassApply;
import com.ys.entity.business.ThrCanvassApplyItem;
import com.ys.entity.flow.YspModel;
import com.ys.entity.hr.ThrOperateCompanyBeian;
import com.ys.entity.sys.TsUserChange;
import com.ys.entity.sys.YsMenu;
import com.ys.entity.sys.YsProcInst;
import com.ys.enume.flow.FlowEnum;
import com.ys.enume.flow.YsProcInstEnum;
import com.ys.mapper.business.ThrCanvassApplyItemMapper;
import com.ys.mapper.business.ThrCanvassApplyMapper;
import com.ys.mapper.hr.HrMapper;
import com.ys.service.business.ThrCanvassApplyService;
import com.ys.service.flow.YspTaskService;
import com.ys.util.CheckUtil;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.Flow;
import com.ys.vo.R;

@Service("thrCanvassApplyService")
public class ThrCanvassApplyServiceImpl implements ThrCanvassApplyService {
	private static final Logger logger = LoggerFactory.getLogger(ThrCanvassApplyServiceImpl.class);

	@Autowired
	private ThrCanvassApplyMapper thrCanvassApplyMapper;

	@Autowired
	private ThrCanvassApplyItemMapper thrCanvassApplyItemMapper;

	@Autowired
	private YspTaskService yspTaskService;

	@Autowired
	private HrMapper hrMapper;

	@Autowired
	private CheckUtil checkUtil;

	/**
	 * 申请新增
	 * @param params
	 * @return
	 * @throws Exception
	 */
	@Override
	@Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
	public R add(Map<String, Object> params, Long menuId) throws Exception {
		logger.info("申请新增传参:"+params);
		// 验证订单号
		if (new ThrCanvassApply().setBid(params.get("bid").toString()).count() > 0) {
			return R.error("该申请单号已存在");
		}
		ThrCanvassApply thrCanvassApply = JSON.parseObject(JSON.toJSONString(params), ThrCanvassApply.class);
		thrCanvassApply.setStatus(1);//状态
		thrCanvassApply.setEffectStock(0);//审批状态
		//获取制单人信息
		TsUserChange tsUserChange = new TsUserChange().setUserId(ShiroUtils.getUserId()).setOrderby("A.CreateTime DESC").queryFirst();
		if(tsUserChange!=null){
			thrCanvassApply.setCreateChangeId(tsUserChange.getId());//制单人变更信息
		}else {
			R.error("未查询到制单人信息！");
		}
		//验证详情信息
		List<Map<String, Object>> paramsNewByItem = new ArrayList<>();
		if(params.get("subData")!=null){
			JSONArray subData = JSON.parseArray(params.get("subData").toString());
			for (int i = 0; i < subData.size(); i++) {
				JSONObject jSONObject = subData.getJSONObject(i);
				Map<String, Object> paramsNew = new HashMap<>();
				for (String key : jSONObject.keySet()) {
					paramsNew.put(key,jSONObject.get(key));
				}
				paramsNew.put("pbid",thrCanvassApply.getBid());//单号
				paramsNewByItem.add(paramsNew);
			}
			String errorMsg = checkParamsByItem(paramsNewByItem, menuId);
			if(errorMsg!=null && !"".equals(errorMsg)){
				return R.error(errorMsg);
			}
		}else {
			return R.error("详情信息为空！");
		}

		//根据运营人工号获取运营人变更id
		TsUserChange tsUserChange1 = new TsUserChange().setUserId(params.get("userId").toString()).setOrderby("A.Id DESC").queryFirst();
		if(tsUserChange1!=null){
			thrCanvassApply.setOperateperson(tsUserChange1.getId());
		}else{
			return R.error( "运营人工号信息有误！");
		}
		//新增运营人员登记申请
		thrCanvassApplyMapper.insert(thrCanvassApply);
		//新增运营人员登记详情
		for(Map<String, Object> item:paramsNewByItem){

			ThrCanvassApplyItem thrCanvassApplyItem = JSON.parseObject(JSON.toJSONString(item), ThrCanvassApplyItem.class);
			thrCanvassApplyItem.setStatus(1);
			thrCanvassApplyItem.setPbid(thrCanvassApply.getBid());
			thrCanvassApplyItem.setAttributes(2);
			thrCanvassApplyItemMapper.insert(thrCanvassApplyItem);
		}
		YsMenu ysMenu = new YsMenu().setId(menuId).queryFirst();
		if (ysMenu.getFlowModelId().longValue() != 0L) {
			YspModel yspModel = new YspModel().setId(ysMenu.getFlowModelId()).queryFirst();
			String codeModel = yspModel.getCode();
			String createUserId = ShiroUtils.getUserId();
			yspTaskService.init(codeModel, thrCanvassApply.getBid(), createUserId);
		}
		return R.ok(AddDto.gotoEdit("/web/business/thrCanvassApply/toEdit?bid=" + thrCanvassApply.getBid()));
	}



	/**
	 * 修改
	 */
	@Override
	public R update(Map<String, Object> params, Long menuId) throws Exception{
		logger.info("申请修改传参:"+params);

		ThrCanvassApply thrCanvassApply = JSON.parseObject(JSON.toJSONString(params), ThrCanvassApply.class);
		// 验证状态
		YsProcInst ysProcInst = new YsProcInst().setBid(thrCanvassApply.getBid()).queryFirst();
		if (ysProcInst == null) {
			return R.error("审批数据不存在，无法编辑");
		} else if (ysProcInst.getStateFlow() != YsProcInstEnum.StateFlow.INIT.value) {
			return R.error("已流转，无法编辑");
		}

		//验证详情信息
		List<Map<String, Object>> paramsNewByItem = new ArrayList<>();
		if(params.get("subData")!=null){
			JSONArray subData = JSON.parseArray(params.get("subData").toString());
			for (int i = 0; i < subData.size(); i++) {
				JSONObject jSONObject = subData.getJSONObject(i);
				Map<String, Object> paramsNew = new HashMap<>();
				for (String key : jSONObject.keySet()) {
					paramsNew.put(key,jSONObject.get(key));
				}
				paramsNew.put("pbid",thrCanvassApply.getBid());//单号
				paramsNewByItem.add(paramsNew);
			}
			String errorMsg = checkParamsByItem(paramsNewByItem, menuId);
			if(errorMsg!=null && !"".equals(errorMsg)){
				return R.error(errorMsg);
			}
		}else {
			return R.error("详情信息为空！");
		}
		//新增、修改运营人员登记详情
		for(Map<String, Object> item:paramsNewByItem){
			ThrCanvassApplyItem thrCanvassApplyItem = JSON.parseObject(JSON.toJSONString(item), ThrCanvassApplyItem.class);
			if(thrCanvassApplyItem.getId()!=null && !"".equals(thrCanvassApplyItem.getId())){
				//修改
				thrCanvassApplyItemMapper.update(thrCanvassApplyItem);
			}else {//新增
				thrCanvassApplyItem.setPbid(thrCanvassApply.getBid());
				thrCanvassApplyItem.setStatus(1);
				thrCanvassApplyItemMapper.insert(thrCanvassApplyItem);
			}
		}


		return R.ok(AddDto.noAction());
	}



	//删除
	@Override
	@Transactional
	public R delete(Long id) throws Exception{
		if (id == null) {
			return R.error("ID不能为空");
		}
		ThrCanvassApply entity = new ThrCanvassApply().setId(id).queryFirst();
		if (entity.getEffectStock() == FlowEnum.EffectStock.EFFECTED.value) {
			return R.error("已生效数据无法删除");
		}
		// 验证是否制单人
		String loginUserId = ShiroUtils.getUserId();
		TsUserChange tsUserChange = new TsUserChange().setId(entity.getCreateChangeId()).queryFirst();
		if (!tsUserChange.getUserId().equals(loginUserId) && !"admin".equals(loginUserId)) {
			return R.error("非制单人，无法删除");
		}
		//删除
		thrCanvassApplyMapper.deleteTrue(id);
		//删除列表信息
		hrMapper.deleteCanvassApplyItemByPbid(entity.getBid());
		//删除流程
		yspTaskService.flowDelete(entity.getBid(), loginUserId);
		return R.ok();
	}


	/**
	 * 流转通过
	 */
	@Override
	@Transactional
	public R flowPass(Long id, String loginUserId) throws Exception {
		ThrCanvassApply entity = new ThrCanvassApply().setId(id).queryFirst();
		Flow f = yspTaskService.flowPass(entity.getBid(), loginUserId);
		if (f.getCode() == Flow.Code.FAILED.value) {
			return R.error(f.getMsg());
		} else {
			if (f.getState() == Flow.State.FINISH.value) {
				flowFinish(entity.getBid());
			}
			return R.ok();
		}
	}

	/**
	 * 流转结束
	 */
	@Override
	@Transactional
	public void flowFinish(String bid) throws Exception {
		ThrCanvassApply thrCanvassApply = new ThrCanvassApply().setBid(bid).queryFirst();
		YsProcInst ysProcInst = new YsProcInst().setBid(thrCanvassApply.getBid()).queryFirst();
		if (ysProcInst.getStateFlow() != YsProcInstEnum.StateFlow.FINISH.value) {
			return;
		}
		Date theDate = new Date();
		thrCanvassApply.setEffectStock(FlowEnum.EffectStock.EFFECTED.value);
		thrCanvassApply.setUpdateTime(theDate);



		//修改主表信息
		thrCanvassApplyMapper.update(thrCanvassApply);


	}


	/**
	 * 详情信息 参数验证
	 */
	public String checkParamsByItem(List<Map<String, Object>> subData, Long menuId) throws Exception {
		String backMsg = "";
		if(subData==null || subData.size()<=0){
			return "详情信息参数为空！";
		}
		for (int i = 0; i < subData.size(); i++) {
			Map<String, Object> msg = subData.get(i);
			if(msg==null){
				backMsg = "详情信息第"+(i+1)+"行的参数为空！";
				continue;
			}
			//验证必填字段的非空；其他字段的长度限制、类型
//			backMsg = checkUtil.checkTableColLengthAndDataType("THR_CanvassApplyItem",listField,msg,ysColItem->ysColItem.getFormEditRequired()!=null && ysColItem.getFormEditRequired() == 1);

			if(msg.get("vgsFrId")!=null && !"".equals(msg.get("vgsFrId")) && !checkUtil.isIDNumberValid(msg.get("vgsFrId").toString())){
				backMsg = "法人身份证号格式有误！";
			}
			if(msg.get("costTelephone")!=null && !"".equals(msg.get("costTelephone")) && !checkUtil.isPhone(msg.get("costTelephone").toString())){
				backMsg = "法人联系方式手机号格式有误！";
			}
			//验证运营公司简称是否重复
			if(msg.get("vgsjc")!=null && !"".equals(msg.get("vgsjc"))){
				//对自身表信息进行验证
				ThrCanvassApplyItem thrCanvassApplyItem = new ThrCanvassApplyItem()
						.setVgsjc(msg.get("vgsjc").toString());
				//若是修改时
				if(msg.get("id")!=null && !"".equals(msg.get("id"))){
					thrCanvassApplyItem.where("A.Id != '"+msg.get("id")+"'");
				}
				int isSame = thrCanvassApplyItem.count();
				if(isSame>0){
					backMsg = "运营公司简称重复！";
				}
				//对运营公司备案表进行验证
				ThrOperateCompanyBeian thrOperateCompanyBeian = new ThrOperateCompanyBeian()
						.setName(msg.get("vgsjc").toString());
				//若是修改时
				if(msg.get("id")!=null && !"".equals(msg.get("id"))){
					thrOperateCompanyBeian.where("A.CanvassApplyItemId != '"+msg.get("id")+"'");
				}
				int isSameByBeiAn = thrOperateCompanyBeian.count();
				if(isSameByBeiAn>0){
					backMsg = "运营公司简称重复！";
				}

			}else{
				backMsg = "运营公司简称为空！";
			}
			for(int j = 0;j < subData.size(); j++ ){
				Map<String, Object> msg1 = subData.get(j);
				boolean issame= false;
				if(j!=i){
					String vgsjcfirst=msg.get("vgsjc").toString();
					String vgsjcsecond=msg1.get("vgsjc").toString();
					if(vgsjcfirst.equals(vgsjcsecond)){
						issame=true;
					}
				}
				if(issame){
					backMsg = "运营公司简称重复！";
				}
			}
		}
		return backMsg;
	}



	//获取列表数据
	@Override
	@Transactional
	public Map<String,Object> getExtraParam( String bid) throws Exception{
		Map<String,Object> entity = new ThrCanvassApply().setBid(bid)
				.addLeftJoin("TS_UserChange AA on AA.Id=A.Operateperson AND 1=1")
				.addLeftJoin("TS_UserInfo U on U.UserId = AA.UserId")
				.addLeftJoin("TS_UserInfo C on C.UserId = U.UserLeader")
				.addLeftJoin("YS_Role PR ON PR.Id = C.RoleId AND 1=1")
				.addLeftJoin("TS_OrganizationInfo PO ON PO.Orgid = C.DeptId AND 1=1")
				.addField("AA.UserId AS userId")
				.addField("AA.UserName AS operatepersonName")
				.addField("AA.RoleName AS roleName")
				.addField("AA.DeptName AS deptName")
				.addField("C.UserName AS superiorpersonnel")
				.addField("PR.Name AS superiorposition")
				.addField("PO.DeptName AS superiordepartment")
				.queryFirstMap();
		return entity;
	}
	//获取子列表数据
	@Override
	@Transactional
	public List<Map<String, Object>> getItemList( String bid) throws Exception{
		List<Map<String, Object>> itemList = new ThrCanvassApplyItem()
				.addField("D.UserId+ '/' + D.UserName AS operateperson")
				.addField("D.DeptName AS deptId")
				.addField("'Amazon' AS platform")
				.addField("E.Name AS institutionName")
				.addField("PO.Vgsbm AS vgsBmp")
				.addField("PO.Vgsjc AS vgsJcp")
				.addLeftJoin("THR_CanvassApply B ON B.Bid = A.Pbid ")
				.addLeftJoin("TS_UserChange D ON D.Id = B.Operateperson")
				.addLeftJoin("TS_OperateOrg E ON E.Id = A.InstitutionId")
				.addLeftJoin("THR_OperateCompanyApply PO ON E.HeadVgsbm = PO.Vgsbm")
				.addLeftJoin("TB_Site S ON S.Id = A.SiteId and 1=1")
				.addLeftJoin("TP_AmazonRegion AR ON AR.Code = S.RegionCode")
				.addField("AR.Name region")
				.addLeftJoin("TB_Country CT ON CT.Id = S.CountryId")
				.addField("CT.Name country")

				.setPbid(bid)
				.queryMap();
		return itemList;
	}


}
